package com.yanti.function;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.yanti.domain.ResponseResult;
import com.yanti.domain.vo.UserWrongAnalysis;
import com.yanti.service.QuestionsService;
import com.yanti.service.UserWrongQuestionsService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Description;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Component
public class WrongQuestionAnalysisFunction {
    @Resource
    private UserWrongQuestionsService userWrongQuestionsService;

    @Resource
    private QuestionsService questionsService;
    // 请求参数类
    public record AnalysisRequest(@JsonProperty(required = true) String userId) {}

    // 响应结果类
    public record AnalysisResult(
            int totalErrors,
            List<UserWrongAnalysis> userWrongAnalysisList,
            Map<String, Long> chapterDistribution,
            double averageDifficulty
    ) {}

    @Bean
    @Description("获取用户错题分析报告")
    public Function<AnalysisRequest, AnalysisResult> questionAnalysis() {
        return request -> {
           // 获取用户错题数据
            ResponseResult<?> result = userWrongQuestionsService.getUserUserWrongQuestionByQuestionId();
            List<UserWrongAnalysis> data = (List<UserWrongAnalysis>) result.getData();
            List<Long> questionIds = data.stream()
                    .map(item -> item.getQuestionsVo().getId())
                    .toList();

            Map<String, Long> wrongQuestionsAnalysis = questionsService.getWrongQuestionsAnalysis(questionIds);
            return new AnalysisResult(
                    data.size(),
                    data,
                    wrongQuestionsAnalysis,
                    data.stream()
                            .mapToInt(difficulty->difficulty.getQuestionsVo().getDifficulty())
                            .average()
                            .orElse(0.0)
            );
        };
    }
}
